package com.qyer.commons.service.health;

import com.codahale.metrics.health.HealthCheck;
import com.qyer.commons.mc.MutableCache;
import com.qyer.commons.place.City;
import com.qyer.commons.place.Country;
import com.qyer.commons.service.model.PlaceDict;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.List;

/**
 * User: Z J Wu Date: 2016/03/07 Time: 21:56 Package: com.qyer.commons.service.hc
 */
public class PlaceHealthCheck extends HealthCheck {

  private MutableCache<PlaceDict<Integer, Country>> countryPlaceDictMC;

  private MutableCache<PlaceDict<Integer, City>> cityPlaceDictMC;

  private int[] testContinentIds;

  private int[] testCountryIds;

  public PlaceHealthCheck(MutableCache<PlaceDict<Integer, Country>> countryPlaceDictMC,
                          MutableCache<PlaceDict<Integer, City>> cityPlaceDictMC,
                          int[] testContinentIds, int[] testCountryIds) {
    this.countryPlaceDictMC = countryPlaceDictMC;
    this.cityPlaceDictMC = cityPlaceDictMC;
    this.testContinentIds = testContinentIds;
    this.testCountryIds = testCountryIds;
  }

  @Override protected Result check() throws Exception {
    if (ArrayUtils.isEmpty(testContinentIds)) {
      return Result.unhealthy("Test continent ids are null.");
    }
    if (ArrayUtils.isEmpty(testCountryIds)) {
      return Result.unhealthy("Test country ids are null.");
    }

    List<Country> countries;
    PlaceDict<Integer, Country> countryPlaceDict = countryPlaceDictMC.getCacheContent();
    for (Integer id : testContinentIds) {
      countries = countryPlaceDict.get(id);
      if (CollectionUtils.isEmpty(countries)) {
        return Result.unhealthy("Empty countries of given continent id(%d).", id);
      }
    }
    List<City> cities;
    PlaceDict<Integer, City> cityPlaceDict = cityPlaceDictMC.getCacheContent();
    for (Integer id : testCountryIds) {
      cities = cityPlaceDict.get(id);
      if (CollectionUtils.isEmpty(cities)) {
        return Result.unhealthy("Empty cities of given country id(%d).", id);
      }
    }

    return Result.healthy("Country/City dict is ok.");
  }
}
